package com.biqee.util;

import java.io.IOException;
import java.io.StringReader;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;
import org.wltea.analyzer.IKSegmentation;
import org.wltea.analyzer.Lexeme;
import org.wltea.analyzer.dic.Dictionary;

public class SegmentUtil {
	private static final Logger logger = Logger.getLogger(TbJuItemUtil.class);
	
	/**
	 * 自动分词
	 * @param str
	 * @return
	 */
	public  static String splitWords(String str){
		StringBuffer sb = new StringBuffer();
	final IKSegmentation ikSeg = new IKSegmentation(new StringReader(str) , true);
		Lexeme l = null;
		try {
			while( (l = ikSeg.next()) != null){
				if(l.getLexemeType()==Lexeme.TYPE_CJK_NORMAL||l.getLexemeType()==Lexeme.TYPE_NUM||l.getLexemeType()==Lexeme.TYPE_LETTER){
					sb.append(l.getLexemeText()+" ");
				}
			}
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
		
		return sb.toString();
		
	}
	
	/**
	 * 智能切分，获取量词后的一个词语  ，合查询关键字
	 * @param str
	 */
	public static String splitSmart(String str){
		StringBuffer sb = new StringBuffer();
		final IKSegmentation ikSeg = new IKSegmentation(new StringReader(str) , false);
		Lexeme l = null;
		boolean findNum = false ;
		int findName = 0; ;
		try {
			while( (l = ikSeg.next()) != null){
				if(findNum==true&&(l.getLexemeType()==Lexeme.TYPE_CJK_NORMAL||l.getLexemeType()==Lexeme.TYPE_LETTER)){
					sb.append(" ");
					sb.append(l.getLexemeText());
					findName ++; 
					if(findName > 3){
						return sb.toString();
					}
					
				}else if(findName==0&&(l.getLexemeType()==Lexeme.TYPE_NUM||l.getLexemeType()==Lexeme.TYPE_NUMCOUNT)){
					findNum = true ;
					sb.append(l.getLexemeText());
				}
			}
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
		
		return null;
		
	}
	
	public static void addDicWords(Collection<String> wordList){
	
		Dictionary.loadExtendWords(wordList);
	}

	public static void addDicWords(String word) {
		Set<String> words = new HashSet<String>();
		words.add(word);
		Dictionary.loadExtendWords(words);
		
	}
	
	
	
	
	
}
